{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pandas按行遍历DataFrame的3种方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import collections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "      <th>C</th>\n",
       "      <th>D</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.329292</td>\n",
       "      <td>0.975468</td>\n",
       "      <td>0.133584</td>\n",
       "      <td>0.224582</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.535746</td>\n",
       "      <td>0.451585</td>\n",
       "      <td>0.713250</td>\n",
       "      <td>0.409770</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.735287</td>\n",
       "      <td>0.667472</td>\n",
       "      <td>0.950622</td>\n",
       "      <td>0.245938</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          A         B         C         D\n",
       "0  0.329292  0.975468  0.133584  0.224582\n",
       "1  0.535746  0.451585  0.713250  0.409770\n",
       "2  0.735287  0.667472  0.950622  0.245938"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.DataFrame(\n",
    "    np.random.random(size=(100000, 4)), \n",
    "    columns=list('ABCD')\n",
    ")\n",
    "df.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100000, 4)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. df.iterrows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 使用方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 A    0.329292\n",
      "B    0.975468\n",
      "C    0.133584\n",
      "D    0.224582\n",
      "Name: 0, dtype: float64\n",
      "0 0.3292915092119043 0.9754683984716609 0.1335841433264423 0.22458227907355865\n"
     ]
    }
   ],
   "source": [
    "for idx, row in df.iterrows():\n",
    "    print(idx, row)\n",
    "    print(idx, row[\"A\"], row[\"B\"], row[\"C\"], row[\"D\"])\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 时间耗费"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 7.82 s, sys: 35.6 ms, total: 7.85 s\n",
      "Wall time: 7.89 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "result = collections.defaultdict(int)\n",
    "for idx, row in df.iterrows():\n",
    "    result[(row[\"A\"], row[\"B\"])] += row[\"A\"] + row[\"B\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. df.itertuples()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 使用方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pandas(Index=0, A=0.3292915092119043, B=0.9754683984716609, C=0.1335841433264423, D=0.22458227907355865)\n",
      "0 0.3292915092119043 0.9754683984716609 0.1335841433264423 0.22458227907355865\n"
     ]
    }
   ],
   "source": [
    "for row in df.itertuples():\n",
    "    print(row)\n",
    "    print(row.Index, row.A, row.B, row.C, row.D)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 时间耗费"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 168 ms, sys: 8.35 ms, total: 177 ms\n",
      "Wall time: 178 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "result = collections.defaultdict(int)\n",
    "for row in df.itertuples():\n",
    "    result[(row.A, row.B)] += row.A + row.B"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. for+zip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 使用方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3292915092119043 0.9754683984716609\n"
     ]
    }
   ],
   "source": [
    "# 既不需要类型检查，也不需要构建namedtuple\n",
    "# 缺点是需要挨个指定变量\n",
    "for A, B in zip(df[\"A\"], df[\"B\"]):\n",
    "    print(A, B)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 时间耗费"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 82.2 ms, sys: 7.05 ms, total: 89.2 ms\n",
      "Wall time: 89.9 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "result = collections.defaultdict(int)\n",
    "for A, B in zip(df[\"A\"], df[\"B\"]):\n",
    "    result[(A, B)] += A + B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
